package com.zhang.boot.core.security;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.zhang.boot.core.constants.ErrorEnum;
import com.zhang.boot.core.exception.BusinessException;
import com.zhang.boot.core.util.security.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.*;
import java.util.stream.Collectors;

/**
 * @Author zhangshaobin
 * @Date 2020/10/30
 * @Description 解密报文
 */
@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {
    private HttpHeaders headers;
    private InputStream body;


    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset) throws Exception {
        if (StrUtil.isEmpty(privateKey)) {
            throw new BusinessException(ErrorEnum.PRIVATE_KEY_ERROR);
        } else {
            this.headers = inputMessage.getHeaders();
            String content = (String) (new BufferedReader(new InputStreamReader(inputMessage.getBody())))
                    .lines()
                    .collect(Collectors.joining(System.lineSeparator()));
            log.info("收到的加密报文:{}", content);
            String decryptBody;
            /*if (content.startsWith("{")) {
                log.info("Unencrypted without decryption:{}", content);
                decryptBody = content;
            } else {*/
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");
            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                String[] var8 = contents;
                int var9 = contents.length;

                for (int var10 = 0; var10 < var9; ++var10) {
                    String value = var8[var10];
                    value = new String(RSAUtil.decrypt(Base64.decode(value), privateKey), charset);
                    json.append(value);
                }
            }
            decryptBody = json.toString();

            log.info("解密后报文:{}", decryptBody);
            //}

            this.body = new ByteArrayInputStream(decryptBody.getBytes());
        }
    }

    @Override
    public InputStream getBody() throws IOException {
        return this.body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }
}
